package com.gcloud.controller.slb.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.gcloud.controller.ResourceProviders;
import com.gcloud.controller.slb.dao.ListenerDao;
import com.gcloud.controller.slb.dao.LoadBalancerDao;
import com.gcloud.controller.slb.dao.VServerGroupDao;
import com.gcloud.controller.slb.entity.Listener;
import com.gcloud.controller.slb.entity.LoadBalancer;
import com.gcloud.controller.slb.entity.VServerGroup;
import com.gcloud.controller.slb.model.DescribeLoadBalancerHTTPListenerAttributeResponse;
import com.gcloud.controller.slb.model.DescribeLoadBalancerHTTPSListenerAttributeResponse;
import com.gcloud.controller.slb.model.DescribeLoadBalancerTCPListenerAttributeResponse;
import com.gcloud.controller.slb.provider.ILoadBalancerListenerProvider;
import com.gcloud.controller.slb.service.ILoadBalancerListenerService;
import com.gcloud.controller.storage.provider.IVolumeProvider;
import com.gcloud.core.condition.ConditionalSlb;
import com.gcloud.core.exception.GCloudException;
import com.gcloud.header.enums.ResourceType;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Transactional(propagation = Propagation.REQUIRES_NEW)
@Service
public class LoadBalancerListenerServiceImpl implements ILoadBalancerListenerService {
	
	@Autowired
    private LoadBalancerDao lberDao;
	
	@Autowired
	private ListenerDao listenerDao;
	
	@Autowired
	private VServerGroupDao vServerGroupDao;
	
	@Override
	public String createLoadBalancerHTTPListener(String loadBalancerId, Integer listenerPort, String vServerGroupId) {
		// TODO Auto-generated method stub
		// 用户资源隔离？
		LoadBalancer lber = lberDao.getById(loadBalancerId);
		if (null == lber) {
            log.debug("找不到负载均衡");
            throw new GCloudException("0120106::找不到负载均衡");
        }
		VServerGroup vServerGroup = vServerGroupDao.getById(vServerGroupId);
		if (null == vServerGroup) {
            log.debug("找不到服务器组");
            throw new GCloudException("0120107::找不到服务器组");
        }

		ILoadBalancerListenerProvider provider = this.getProvider(lber.getProvider());
		String resposne = provider.createLoadBalancerHTTPListener(loadBalancerId, listenerPort, vServerGroupId);

        return resposne;
	}

	@Override
	public String createLoadBalancerHTTPSListener(String loadBalancerId, Integer listenerPort, String vServerGroupId,
			String serverCertificateId) {
		// TODO Auto-generated method stub
		// 用户资源隔离？
		LoadBalancer lber = lberDao.getById(loadBalancerId);
		if (null == lber) {
            log.debug("找不到负载均衡");
            throw new GCloudException("0120207::找不到负载均衡");
        }
		VServerGroup vServerGroup = vServerGroupDao.getById(vServerGroupId);
		if (null == vServerGroup) {
            log.debug("找不到服务器组");
            throw new GCloudException("0120208::找不到服务器组");
        }
		ILoadBalancerListenerProvider provider = this.getProvider(lber.getProvider());
		String resposne = provider.createLoadBalancerHTTPSListener(loadBalancerId, listenerPort, vServerGroupId, vServerGroupId);

        return resposne;
	}

	@Override
	public String createLoadBalancerTCPListener(String loadBalancerId, Integer listenerPort, String vServerGroupId) {
		// TODO Auto-generated method stub
		LoadBalancer lber = lberDao.getById(loadBalancerId);
		if (null == lber) {
            log.debug("找不到负载均衡");
            throw new GCloudException("0120306::找不到负载均衡");
        }
		VServerGroup vServerGroup = vServerGroupDao.getById(vServerGroupId);
		if (null == vServerGroup) {
            log.debug("找不到服务器组");
            throw new GCloudException("0120307::找不到服务器组");
        }
		ILoadBalancerListenerProvider provider = this.getProvider(lber.getProvider());
		String resposne = provider.createLoadBalancerTCPListener(loadBalancerId, listenerPort, vServerGroupId);

        return resposne;
	}

	@Override
	public void setLoadBalancerHTTPListenerAttribute(String listenerId, String vServerGroupId) {
		// TODO Auto-generated method stub
		Listener listener = listenerDao.getById(listenerId);
		if (null == listener) {
			log.debug("找不到负载均衡监听器");
            throw new GCloudException("0120403::找不到负载均衡监听器");
        }
		VServerGroup vServerGroup = vServerGroupDao.getById(vServerGroupId);
		if (vServerGroup == null) {
			log.debug("找不到服务器组");
            throw new GCloudException("0120404::找不到服务器组");
		}

		try {
			List<String> updateField = new ArrayList<String>();
			updateField.add(listener.updateVserverGroupId(vServerGroupId));
			updateField.add(listener.updateVserverGroupName(vServerGroup.getName()));
			updateField.add(listener.updateUpdatedAt(new Date()));
			listenerDao.update(listener, updateField);
			ILoadBalancerListenerProvider provider = this.getProvider(listener.getProvider());
			provider.setLoadBalancerHTTPListenerAttribute(listener.getProviderRefId(), vServerGroup.getProviderRefId());
		} catch (Exception e) {
			log.debug("配置负载均衡监听器失败");
            throw new GCloudException("0120405::配置负载均衡监听器失败");
		}
		
	}

	@Override
	public void setLoadBalancerHTTPSListenerAttribute(String listenerId, String vServerGroupId,
			String serverCertificateId) {
		// TODO Auto-generated method stub
		Listener listener = listenerDao.getById(listenerId);
		if (null == listener) {
			log.debug("找不到负载均衡监听器");
            throw new GCloudException("0120504::找不到负载均衡监听器");
        }
		VServerGroup vServerGroup = vServerGroupDao.getById(vServerGroupId);
		if (vServerGroup == null) {
			log.debug("找不到服务器组");
            throw new GCloudException("0120505::找不到服务器组");
		}
		//判断证书ID是否存在，由于openstack不支持证书管理，改功能暂时不可用
		try {
			List<String> updateField = new ArrayList<String>();
			updateField.add(listener.updateVserverGroupId(vServerGroupId));
			updateField.add(listener.updateVserverGroupName(vServerGroup.getName()));
			updateField.add(listener.updateUpdatedAt(new Date()));
			updateField.add(listener.updateServerCertificateId(null));
			listenerDao.update(listener, updateField);
			ILoadBalancerListenerProvider provider = this.getProvider(listener.getProvider());
			provider.setLoadBalancerHTTPSListenerAttribute(listener.getProviderRefId(), vServerGroup.getProviderRefId(), serverCertificateId);
		} catch (Exception e) {
			log.debug("配置负载均衡监听器失败");
            throw new GCloudException("0120506::配置负载均衡监听器失败");
		}
		
	}

	@Override
	public void setLoadBalancerTCPListenerAttribute(String listenerId, String vServerGroupId) {
		// TODO Auto-generated method stub
		Listener listener = listenerDao.getById(listenerId);
		if (null == listener) {
            log.debug("找不到负载均衡");
            throw new GCloudException("0120603::找不到负载均衡");
        }
		VServerGroup vServerGroup = vServerGroupDao.getById(vServerGroupId);
		if (vServerGroup == null) {
			log.debug("找不到服务器组");
            throw new GCloudException("0120604::找不到服务器组");
		}
		try {
			List<String> updateField = new ArrayList<String>();
			updateField.add(listener.updateVserverGroupId(vServerGroupId));
			updateField.add(listener.updateVserverGroupName(vServerGroup.getName()));
			updateField.add(listener.updateUpdatedAt(new Date()));
			listenerDao.update(listener, updateField);
			ILoadBalancerListenerProvider provider = this.getProvider(listener.getProvider());
			provider.setLoadBalancerTCPListenerAttribute(listener.getProviderRefId(), vServerGroup.getProviderRefId());
		} catch (Exception e) {
			log.debug("配置负载均衡监听器失败");
            throw new GCloudException("0120605::配置负载均衡监听器失败");
		}
	}

	@Override
	public void deleteLoadBalancerListener(String listenerId) {
		// TODO Auto-generated method stub
		Listener listener = listenerDao.getById(listenerId);
		if (null == listener) {
			log.debug("找不到负载均衡监听器");
            throw new GCloudException("0121002::找不到负载均衡监听器");
        }
		try {
			listenerDao.deleteById(listenerId);
			ILoadBalancerListenerProvider provider = this.getProvider(listener.getProvider());
			provider.deleteLoadBalancerListener(listener.getProviderRefId());
		} catch(Exception e) {
			log.debug("删除负载均衡监听器失败");
            throw new GCloudException("0121003::删除负载均衡监听器失败");
		}	
	}

	@Override
	public DescribeLoadBalancerHTTPListenerAttributeResponse describeLoadBalancerHTTPListenerAttribute(String listenerId) {
		// TODO Auto-generated method stub
		Listener listener = listenerDao.getById(listenerId);
		if (null == listener) {
			log.debug("找不到负载均衡监听器");
            throw new GCloudException("0120702::找不到负载均衡监听器");
        }
		DescribeLoadBalancerHTTPListenerAttributeResponse response = new DescribeLoadBalancerHTTPListenerAttributeResponse();
		response.setListenerPort(listener.getListenerPort());
		response.setStatus(listener.getStatus());
		response.setvServerGroupId(listener.getVserverGroupId());
		return response;
	}

	@Override
	public DescribeLoadBalancerHTTPSListenerAttributeResponse describeLoadBalancerHTTPSListenerAttribute(String listenerId) {
		// TODO Auto-generated method stub
		Listener listener = listenerDao.getById(listenerId);
		if (null == listener) {
			log.debug("找不到负载均衡监听器");
            throw new GCloudException("0120802::找不到负载均衡监听器");
        }
		DescribeLoadBalancerHTTPSListenerAttributeResponse response = new DescribeLoadBalancerHTTPSListenerAttributeResponse();
		response.setListenerPort(listener.getListenerPort());
		response.setServerCertificateId(listener.getServerCertificateId());
		response.setStatus(listener.getStatus());
		response.setvServerGroupId(listener.getVserverGroupId());
		return response;
	}

	@Override
	public DescribeLoadBalancerTCPListenerAttributeResponse describeLoadBalancerTCPListenerAttribute(String listenerId) {
		// TODO Auto-generated method stub
		Listener listener = listenerDao.getById(listenerId);
		if (null == listener) {
			log.debug("找不到负载均衡监听器");
            throw new GCloudException("0120902::找不到负载均衡监听器");
        }
		DescribeLoadBalancerTCPListenerAttributeResponse response = new DescribeLoadBalancerTCPListenerAttributeResponse();
		response.setListenerPort(listener.getListenerPort());
		response.setStatus(listener.getStatus());
		response.setvServerGroupId(listener.getVserverGroupId());
		return response;
	}
	
	private ILoadBalancerListenerProvider getProvider(int providerType) {
		ILoadBalancerListenerProvider provider = ResourceProviders.checkAndGet(ResourceType.SLB_LISTENER, providerType);
        return provider;
    }
}
